package com.supermap.desktop.ui;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Comparator;

import org.w3c.dom.Element;

import com.supermap.desktop.Application;
import com.supermap.desktop.PluginInfo;
import com.supermap.desktop.Interface.IBaseItem;
import com.supermap.desktop.Interface.ICtrlAction;
import com.supermap.desktop.Interface.IForm;
import com.supermap.desktop.enums.XMLCommandType;

public class XMLCommand extends XMLCommandBase implements Comparator<XMLCommand>, Comparable<XMLCommand> {

	private boolean enable = true;
	private String ctrlActionClass = "";
	private ICtrlAction ctrlAction = null;

	public XMLCommand(PluginInfo pluginInfo) {
		super(pluginInfo);
		this.commandType = XMLCommandType.COMMAND;
	}

	public XMLCommand(XMLCommandBase parent) {
		super(parent);
		this.commandType = XMLCommandType.COMMAND;
	}

	public XMLCommand(PluginInfo pluginInfo, XMLCommandBase parent) {
		super(pluginInfo, parent);
		this.commandType = XMLCommandType.COMMAND;
	}

	@Override
	public boolean initialize(Element xmlNodeCommand) {
		super.initialize(xmlNodeCommand);

		// 是否可用
		try {
			if (xmlNodeCommand.getAttribute(g_AttributionEnabled).equalsIgnoreCase(g_ValueFalse)) {
				this.setEnabled(false);
			} else {
				this.setEnabled(true);
			}
		} catch (Exception ex) {
		}

		// ctrlaction class name
		try {
			this.setCtrlActionClass(xmlNodeCommand.getAttribute(g_OnAction));
		} catch (Exception ex) {
		}

		// 提示信息
		try {
			String tooltip = xmlNodeCommand.getAttribute(g_AttributionScreenTip);
			if (tooltip == null || tooltip == "") {
				tooltip = this.getLabel();
			}
			this.setTooltip(tooltip);
		} catch (Exception ex) {
		}

		// 快捷方式
		try {
			this.setShortCutKeys(xmlNodeCommand.getAttribute(g_AttributionShortcutKey));
		} catch (Exception ex) {
		}

		// 帮助链接
		try {
			this.setHelpURL(xmlNodeCommand.getAttribute(g_AttributionHelpURL));
		} catch (Exception ex) {
		}

		// 图片信息
		try {
			this.setImageFile(xmlNodeCommand.getAttribute(g_AttributionImage));
		} catch (Exception ex) {
		}

		// // 提示信息图片
		// try {
		// this.setTooltipImageFile(xmlNodeCommand.getAttribute(g_AttributionScreenTipImage));
		// }catch (Exception ex) { }

		// 描述信息
		try {
			this.setDescription(xmlNodeCommand.getAttribute(g_AttributionDescription));
		} catch (Exception ex) {
		}

		return true;
	}

	public boolean getEnabled() {
		return this.enable;
	}

	public void setEnabled(boolean enable) {
		this.enable = enable;
	}

	public String getCtrlActionClass() {
		return this.ctrlActionClass;
	}

	public void setCtrlActionClass(String ctrlActionClass) {
		this.ctrlActionClass = ctrlActionClass;
	}

	public ICtrlAction getCtrlAction() {
		return this.ctrlAction;
	}

	public void setCtrlAction(ICtrlAction ctrlAction) {
		this.ctrlAction = ctrlAction;
	}

	// Image this.tooltipImage;
	// public Image TooltipImage
	// {
	// get
	// {
	// return this.tooltipImage;
	// }
	// set
	// {
	// if (this.tooltipImage != null)
	// {
	// this.tooltipImage.Dispose();
	// this.tooltipImage = null;
	// }
	// this.tooltipImage = value;
	// }
	// }
	//
	// String this.tooltipImageFile = "";
	// public String TooltipImageFile
	// {
	// get
	// {
	// return this.tooltipImageFile;
	// }
	// set
	// {
	// if (this.tooltipImage != null)
	// {
	// this.tooltipImage.Dispose();
	// this.tooltipImage = null;
	// }
	// this.tooltipImageFile = value;
	// }
	// }

	String tooltip = "";

	public String getTooltip() {
		return this.tooltip;
	}

	public void setTooltip(String tooltip) {
		this.tooltip = tooltip;
	}

	String shortCutKeys = "";

	public String getShortCutKeys() {
		return this.shortCutKeys;
	}

	public void setShortCutKeys(String shortCutKeys) {
		this.shortCutKeys = shortCutKeys;
	}

	String helpURL = "";

	public String getHelpURL() {
		return this.helpURL;
	}

	public void setHelpURL(String helpURL) {
		this.helpURL = helpURL;
	}

	String imageFile = "";

	public String getImageFile() {
		return this.imageFile;
	}

	public void setImageFile(String imageFile) {
		this.imageFile = imageFile;
	}

	String description = "";

	public String getDescription() {
		return this.description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	// Bitmap this.image;
	// public System.Drawing.Bitmap Image
	// {
	// get
	// {
	// return this.image;
	// }
	// set
	// {
	// if (this.image != null)
	// {
	// this.image.Dispose();
	// this.image = null;
	// }
	// if (this.largeImage != null)
	// {
	// this.largeImage.Dispose();
	// this.largeImage = null;
	// }
	// this.image = value;
	// }
	// }
	//
	// Bitmap this.largeImage;
	// public System.Drawing.Bitmap LargeImage
	// {
	// get
	// {
	// return this.largeImage;
	// }
	// set
	// {
	// if (this.largeImage != null)
	// {
	// this.largeImage.Dispose();
	// this.largeImage = null;
	// }
	// this.largeImage = value;
	// }
	// }
	//
	// CommandSizeMode this.sizeMode = CommandSizeMode.Small;
	// public CommandSizeMode SizeMode
	// {
	// get
	// {
	// return this.sizeMode;
	// }
	// set
	// {
	// this.sizeMode = value;
	// }
	// }

	protected Boolean canMerge = false;

	public Boolean canMerge() {
		return this.canMerge;
	}

	// public Assembly getCtrlActionAssembly()
	// {
	// Assembly assemblyAction = null;
	//
	// // 记录在最近文件列表文件中的assemblyName是绝对路径，换了其他的程序运行目录就找不到了所以需要重新获取一下 [11/29/2011
	// zhoujt]
	// String assemblyFileName =
	// CommonToolkit.PathWrap.GetFullPathName(Path.GetFileName(this.assemblyFileName));
	// if (assemblyFileName == null ||
	// assemblyFileName == "" ||
	// assemblyFileName.Length == 0)
	// {
	// return assemblyAction;
	// }
	//
	// String assemblyName = Path.GetFileNameWithoutExtension(assemblyFileName);
	//
	// //查找一下是否已经加载进来了
	// Assembly[] assemblys = AppDomain.CurrentDomain.GetAssemblies();
	//
	// foreach (Assembly assembly in assemblys)
	// {
	// //加载的底层动态库，非.net托管程序集，不支持assembly.Location等方法
	// if (!assembly.IsDynamic)
	// {
	// assemblyAction = null;
	// if (assembly.FullName.ToLower().IndexOf(assemblyName.ToLower()) == 0 ||
	// assembly.Location.ToLower().Equals(assemblyName.ToLower()))
	// {
	// assemblyAction = assembly;
	// break;
	// }
	// }
	// }
	//
	// // 如果该Assembly未加载，则加载一下
	// if (assemblyAction == null &&
	// assemblyFileName != null &&
	// assemblyFileName.Length != 0)
	// {
	// try
	// {
	// assemblyAction = System.Reflection.Assembly.LoadFrom(assemblyFileName);
	// }
	// catch
	// {
	//
	// }
	// }
	//
	// return assemblyAction;
	// }

	public Boolean buildCtrlAction(IBaseItem caller) {
		Boolean result = false;
		try {
			XMLCommandBase baseContainer = findBaseContainer();
			// if (baseContainer instanceof XMLRibbonTab)
			// {
			// XMLRibbonTab tab = baseContainer as XMLRibbonTab;
			// result = this.BuildCtrlAction(caller, tab.AssociatedForm);
			// }
			// else if (baseContainer is XMLStartMenu)
			// {
			// result = this.BuildCtrlAction(caller, null);
			// }
			// else if (baseContainer is XMLStatusBar)
			// {
			// XMLStatusBar statusBar = baseContainer as XMLStatusBar;
			// result = this.BuildCtrlAction(caller, statusBar.AssociatedForm);
			// }
		} catch (Exception ex) {
			Application.getActiveApplication().getOutput().output(ex);
		}

		return result;
	}

	public Boolean buildCtrlAction(IBaseItem caller, IForm associatedForm) {
		try {
			// if (!String.IsNullOrEmpty(this.CtrlActionClass)
			// && this.CtrlActionClass.Equals(g_ScriptCodeFlag))
			// {
			// //根据className属性确定是否为动态脚本
			// //String code = itemNode.InnerText;
			// this.CtrlAction =
			// Application.ActiveApplication.Script.CompileCtrlActionCodeSnippet(this.CodeType,
			// this.DynamicCode);
			// }
			// else if (!String.IsNullOrEmpty(this.CtrlActionClass)
			// &&
			// System.IO.File.Exists(CommonToolkit.PathWrap.GetFullPathName(this.CtrlActionClass)))
			// {
			// String extension =
			// System.IO.Path.GetExtension(this.CtrlActionClass);
			// CodeType codeType = CodeType.CSharp;
			// if
			// (extension.ToLower().Equals(Properties.CoreResources.String_VBExtension))
			// {
			// codeType = CodeType.VB;
			// }
			// this.CtrlAction =
			// Application.ActiveApplication.Script.CompileCtrlActionClass(codeType,
			// new String[] {
			// CommonToolkit.PathWrap.GetFullPathName(this.CtrlActionClass) });
			// }
			// else
			// {
			// Assembly assemblyAction = GetCtrlActionAssembly();
			// if (assemblyAction == null)
			// {
			// return false;
			// }
			//
			// String exceptionMessage = "";
			// try
			// {
			// Type type = assemblyAction.GetType(this.CtrlActionClass);
			// if (type != null)
			// {
			// ConstructorInfo constructor = type.GetConstructor(new Type[] {
			// typeof(IBaseItem), typeof(IForm) });
			// if (constructor != null)
			// {
			// this.ctrlAction = constructor.Invoke(new object[] { caller,
			// associatedForm }) as ICtrlAction;
			// }
			// else
			// {
			// constructor = type.GetConstructor(Type.EmptyTypes);
			// this.ctrlAction = constructor.Invoke(null) as ICtrlAction;
			// this.ctrlAction.Caller = caller;
			// (this.ctrlAction as CtrlAction).FormClass = associatedForm;
			// }
			// }
			// }
			// catch (Exception ex)
			// {
			// exceptionMessage = ex.StackTrace;
			// }
			// }
			//
			// IShortcut shortcut = Application.ActiveApplication.MainForm as
			// IShortcut;
			// if (shortcut != null)
			// {
			// shortcut.RegisterShortcut(getID(this.ShortCutKeys),
			// this.CtrlAction);
			// }
			// if (this.ctrlAction != null
			// && !String.IsNullOrEmpty(HelpURL))
			// {
			// this.ctrlAction.HelpURL = HelpURL;
			// }
		} catch (Exception ex) {
			Application.getActiveApplication().getOutput().output(ex);
		}

		return this.ctrlAction != null;
	}

	public Boolean loadTooltipImage() {
		// this.tooltipImage =
		// CommonToolkit.RibbonWrap.GetBitmap(this.tooltipImageFile);
		// return this.tooltipImage != null;
		return false;
	}

	public Boolean loadImage() {
		// this.image = CommonToolkit.RibbonWrap.GetBitmap(this.ImageFile);
		// return this.image != null;
		return false;
	}

	public Boolean loadLargeImage() {
		// String largeImagePath = Path.ChangeExtension(this.imageFile,
		// _XMLTag.g_ValueLargeImagePostfix +
		// Path.GetExtension(this.imageFile));
		// this.largeImage =
		// CommonToolkit.RibbonWrap.GetBitmap(largeImagePath);
		// return this.largeImage != null;
		return false;
	}

	public void merge(XMLCommand otherCommand) {
	}

	// public static Keys getID(String names)
	// {
	// Keys result = Keys.None;
	// try
	// {
	// if (names != null && names.Length > 0)
	// {
	// String[] items = names.Split(new String[] {
	// Properties.CoreResources.String_ShortCutKeySplit },
	// StringSplitOptions.RemoveEmptyEntries);
	// for (Int32 i = 0; i < items.Length; i++)
	// {
	// Int32 start =
	// items[i].IndexOf(Properties.CoreResources.String_ShortCutStart);
	// Int32 end =
	// items[i].IndexOf(Properties.CoreResources.String_ShortCutEnd);
	// if (start > -1 && end > -1)
	// {
	// items[i] = items[i].Substring(start + 1, end - start - 1);
	// }
	// Keys temp = CommonToolkit.KeyboardWrap.GetKeysByName(items[i]);
	// result |= temp;
	// }
	// }
	// }catch (Exception ex) {
	// Application.getActiveApplication().getOutput().output(ex);
	// }
	// return result;
	// }
	//
	// public void setShortcutKeys(Keys shortcutKey)
	// {
	// String result = _XMLTag.g_Empty;
	// if (shortcutKey != Keys.None)
	// {
	// Keys temp = shortcutKey;
	// if ((shortcutKey & Keys.Shift) == Keys.Shift)
	// {
	// result += Properties.CoreResources.String_ShortCutStart +
	// Keys.Shift.ToString()
	// + Properties.CoreResources.String_ShortCutEnd +
	// Properties.CoreResources.String_ShortCutKeySplit;
	// temp ^= Keys.Shift;
	// }
	// if ((shortcutKey & Keys.Alt) == Keys.Alt)
	// {
	// result += Properties.CoreResources.String_ShortCutStart +
	// Keys.Alt.ToString()
	// + Properties.CoreResources.String_ShortCutEnd +
	// Properties.CoreResources.String_ShortCutKeySplit;
	// temp ^= Keys.Alt;
	// }
	// if ((shortcutKey & Keys.Control) == Keys.Control)
	// {
	// //Keys.Control.ToString()为“Control”
	// result += Properties.CoreResources.String_ShortCutStart +
	// Properties.CoreResources.String_ShortCut_Ctrl
	// + Properties.CoreResources.String_ShortCutEnd +
	// Properties.CoreResources.String_ShortCutKeySplit;
	// temp ^= Keys.Control;
	// }
	// result += Properties.CoreResources.String_ShortCutStart + temp.ToString()
	// + Properties.CoreResources.String_ShortCutEnd;
	// }
	//
	// this.shortCutKeys = result;
	// }

	/**
	 * 使用指定的parent构造一个跟自己一个类型的对象
	 * 
	 * @param parent
	 * @return
	 */
	private XMLCommandBase createNew(XMLCommandBase parent) {
		XMLCommand result = null;
		try {
			// if (this is XMLRibbonButton)
			// {
			// if (this is XMLRibbonButtonDropdown)
			// {
			// result = new XMLRibbonButtonDropdown(parent);
			// }
			// else if (this is XMLRibbonCheckBox)
			// {
			// result = new XMLRibbonCheckBox(parent);
			// }
			// else if (this is XMLRibbonColorButton)
			// {
			// result = new XMLRibbonColorButton(parent);
			// }
			// else if (this is XMLRibbonGalleryItem)
			// {
			// result = new XMLRibbonGalleryItem(parent);
			// }
			// else if (this is XMLBackstageButtonDropdown)
			// {
			// result = new XMLBackstageButtonDropdown(parent);
			// }
			// else
			// {
			// result = new XMLRibbonButton(parent);
			// }
			// }
			/* else */if (this instanceof XMLMenuCommand) {
				if (this instanceof XMLMenuButtonDropdown) {
					result = new XMLMenuButtonDropdown(this.getPluginInfo(), (XMLMenuGroup) parent);
				} else if (this instanceof XMLMenuButton) {
					result = new XMLMenuButton(this.getPluginInfo(), (XMLMenuGroup) parent);
				}
			} else if (this instanceof XMLButton) {
				result = new XMLButton(this.getPluginInfo(), (XMLCommand) parent);
			} else if (this instanceof XMLLabel) {
				result = new XMLLabel(this.getPluginInfo(), (XMLCommand) parent);
			} else if (this instanceof XMLTextbox) {
				result = new XMLTextbox(this.getPluginInfo(), (XMLCommand) parent);
			} else if (this instanceof XMLComboBox) {
				result = new XMLComboBox(this.getPluginInfo(), (XMLCommand) parent);
			} else if (this instanceof XMLSeparator) {
				result = new XMLSeparator(this.getPluginInfo(), (XMLCommand) parent);
			}
			// else
			// {
			// result = new XMLContextMenuCommand(parent as
			// XMLContextMenuGroup);
			// }
			// }
			// else if (this is XMLRibbonGroupDialogBoxLauncher)
			// {
			// result = new XMLRibbonGroupDialogBoxLauncher(parent as
			// XMLRibbonGroup);
			// }
			// else if (this is XMLRibbonComboBox)
			// {
			// result = new XMLRibbonComboBox(parent);
			// }
			// else if (this is XMLRibbonTextBox)
			// {
			// result = new XMLRibbonTextBox(parent);
			// }
			// else if (this is XMLRibbonLabel)
			// {
			// result = new XMLRibbonLabel(parent);
			// }
			// else if (this is XMLRibbonGallery)
			// {
			// result = new XMLRibbonGallery(parent);
			// }
			// else if (this is XMLRibbonBox)
			// {
			// result = new XMLRibbonBox(parent);
			// }
			// else if (this is XMLRibbonSeparator)
			// {
			// result = new XMLRibbonSeparator(parent);
			// }
			// else if (this is XMLRibbonIntegerUpDown)
			// {
			// result = new XMLRibbonIntegerUpDown(parent);
			// }
			// else if (this is XMLBackstageTab)
			// {
			// result = new XMLBackstageTab(parent);
			// }
		} catch (Exception ex) {
			Application.getActiveApplication().getOutput().output(ex);
		}

		return result;
	}

	@Override
	public XMLCommandBase saveToPluginInfo(PluginInfo pluginInfo, XMLCommandBase parent) {
		XMLCommand result = null;
		try {
			// if (this.PluginInfoList.Contains(pluginInfo))
			// {
			// result = CreateNew(parent) as XMLCommand;
			// result.Index = this.Index;
			// result.Label = this.Label;
			// result.Key = this.Key;
			// result.ImageFile = this.ImageFile;
			// result.Visible = this.Visible;
			// result.Enabled = this.Enabled;
			// result.CtrlActionClass = this.CtrlActionClass;
			// result.CodeType = this.CodeType;
			// result.DynamicCode = this.DynamicCode;
			// result.Style = this.Style;
			// result.SizeMode = this.SizeMode;
			// result.Tooltip = this.Tooltip;
			// result.HelpURL = this.HelpURL;
			// result.ShortCutKeys = this.ShortCutKeys;
			// result.TooltipImageFile = this.TooltipImageFile;
			// result.Description = this.Description;
			// result.CustomProperty = this.CustomProperty;
			// }
		} catch (Exception ex) {
			Application.getActiveApplication().getOutput().output(ex);
		}

		return result;
	}

	@Override
	public void clearResources() {
		try {
			// if (this.Image != null)
			// {
			// this.Image.Dispose();
			// this.Image = null;
			// }
			// if (this.LargeImage != null)
			// {
			// this.LargeImage.Dispose();
			// this.LargeImage = null;
			// }
			// if (this.TooltipImage != null)
			// {
			// this.TooltipImage.Dispose();
			// this.TooltipImage = null;
			// }
			// if (this.CtrlAction != null)
			// {
			// this.CtrlAction = null;
			// }
		} catch (Exception ex) {
			Application.getActiveApplication().getOutput().output(ex);
		}
	}

	@Override
	public boolean containsAction(Type ctrlActionType) {
		Boolean result = false;
		try {
			// if (!String.IsNullOrEmpty(this.CtrlActionClass)) {
			// result = this.CtrlActionClass.Equals(ctrlActionType.ToString());
			// }
		} catch (Exception ex) {
			Application.getActiveApplication().getOutput().output(ex);
		}

		return result;
	}

	protected void setAttributeCodeType(Element xmlElement) {

		try {
			// if (xmlElement != null
			// && !String.IsNullOrEmpty(this.CtrlActionClass)
			// && this.CtrlActionClass.Equals(_XMLTag.g_ScriptCodeFlag))
			// {
			// if (this.CodeType == CodeType.CSharp)
			// {
			// xmlElement.SetAttribute(_XMLTag.g_AttributionCodeType,
			// _XMLTag.g_ValueCodeType_CS);
			// }
			// else
			// {
			// xmlElement.SetAttribute(_XMLTag.g_AttributionCodeType,
			// _XMLTag.g_ValueCodeType_VB);
			// }
			// }
		} catch (Exception ex) {
			Application.getActiveApplication().getOutput().output(ex);
		}
	}

	// protected XmlCDataSection createDynamicCodeNode(XmlDocument document) {
	// XmlCDataSection dynamicCodeNode = null;
	// try
	// {
	// if (document != null
	// && !String.IsNullOrEmpty(this.DynamicCode))
	// {
	// dynamicCodeNode = document.CreateCDataSection(this.DynamicCode);
	// }
	// }catch (Exception ex) {
	// Application.getActiveApplication().getOutput().output(ex);
	// }
	//
	// return dynamicCodeNode;
	// }

	@Override
	public XMLCommandBase clone(XMLCommandBase parent) {
		XMLCommand result = null;
		try {
			result = (XMLCommand) createNew(parent);

			result.setIsDesigning(this.getIsDesigning());
			result.setIndex(this.getIndex());
			result.setLabel(this.getLabel());
			result.setID(this.getID());
			result.setImageFile(this.getImageFile());
			result.setVisible(this.getVisible());
			result.setEnabled(this.getEnabled());
			result.setCtrlActionClass(this.getCtrlActionClass());
			// result.setCodeType(this.getCodeType());
			// result.setDynamicCode(this.getDynamicCode());
			// result.setStyle(this.getStyle());
			// result.setSizeMode(this.getSizeMode());
			result.setTooltip(this.getTooltip());
			result.setHelpURL(this.getHelpURL());
			result.setShortCutKeys(this.getShortCutKeys());
			// result.setTooltipImageFile(this.getTooltipImageFile());
			result.setDescription(this.getDescription());
			result.setCustomProperty(this.getCustomProperty());
		} catch (Exception ex) {
			Application.getActiveApplication().getOutput().output(ex);
		}

		return result;
	}

	@Override
	public int compare(XMLCommand o1, XMLCommand o2) {
		return o1.getIndex() - o2.getIndex();
	}

	@Override
	public int compareTo(XMLCommand o) {
		return this.getIndex() - o.getIndex();
	}
}
